package com.demo.chapter5stream2;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FlatMapDemo {

	//对"Goodbye", "World"里面的每个字符排重
	public static void demo1(){
		String[] words = {"Goodbye", "World"};
		//Stream<String[]>
		List<String> list = Stream.of(words).map(w -> w.split(""))
			//Arrays::stream把数组转换为Stream：Stream<String> stream = Arrays.stream(String[])
			//flatMap把一个流中的每一个值转换为另一个流，然后把所有的流连接起来成为一个流
			.flatMap(Arrays::stream)
			.distinct()
			.collect(Collectors.toList());
		System.out.println(list);
	}

	//给定两个数字列表，返回所有对数，例如列表[1,2,3]和[3,4]，返回[(1,3),(1,4),(2,3),(2,4),(3,3),(3,4)]
	public static void demo2(){
		List<Integer> number1 = Arrays.asList(1, 2, 3);
		List<Integer> number2 = Arrays.asList(3, 4);
		number1.stream()
			.flatMap(i -> number2.stream().map(j -> new int[]{i, j}))
			.forEach(x -> {
				int[] result = (int[])x;
				System.out.println(result[0] + "," + result[1]);
			});
	}

	//再过滤一下，只保留总和能被3整除的
	public static void demo3(){
		List<Integer> number1 = Arrays.asList(1, 2, 3);
		List<Integer> number2 = Arrays.asList(3, 4);
		number1.stream()
		.flatMap(i -> number2.stream().filter(j -> (i + j) % 3 == 0).map(j -> new int[]{i, j}))
		.forEach(x -> {
			int[] result = (int[])x;
			System.out.println(result[0] + "," + result[1]);
		});
	}

	public static void main(String[] args) {
		demo1();
		System.out.println("==============");
		demo2();
		System.out.println("==============");
		demo3();
	}

}
